const pool = require('./db');
const cryptoUtil = require('./crypto');

// 获取服务器信息
async function getServerInfo(accountName, targetHost) {
    try {
        const [rows] = await pool.execute(
            `SELECT a.*, c.username, c.encrypted_pwd
             FROM allowed_accounts a
             JOIN credentials c ON a.credential_id = c.id
             WHERE a.account_name = ? AND a.target_host = ?`,
            [accountName, targetHost]
        );

        const [RootPasswd] = await pool.execute(
            `SELECT a.*, c.username, c.encrypted_pwd
             FROM allowed_accounts a
             JOIN credentials c ON a.credential_id = c.id
             WHERE a.account_name = 'root' AND a.target_host = ?`,
            [targetHost]
        );

        if (rows.length === 0) return null;
        if (RootPasswd.length === 0) {
            logger('[ERROR]:未找到root用户的密码信息');
            return { success: false, error: '未找到root用户的密码信息' };
        }

        // 解密密码
        const decryptedPwd = cryptoUtil.decrypt(rows[0].encrypted_pwd);

        return {
            host: rows[0].target_host,
            port: rows[0].target_port,
            username: rows[0].username,
            password: decryptedPwd,
            rootPassword: RootPasswd[0].encrypted_pwd
        };

    } catch (error) {
        logger(`[ERROR]:获取服务器信息失败: ${error.message}`);
        return { success: false, error: error.message}
    }
}

// 新增服务器信息
async function addServerInfo(serverData) {
    try {
        // 加密密码
        const encryptedPwd = cryptoUtil.encrypt(serverData.password);

        // 先插入凭证
        const [credResult] = await pool.execute(
            'INSERT INTO credentials (username, encrypted_pwd, description, c_host) VALUES (?, ?, ?, ?)',
            [serverData.username, encryptedPwd, serverData.description || '', serverData.host]
        );

        // 再插入服务器信息
        await pool.execute(
            'INSERT INTO allowed_accounts (account_name, target_type, target_host, target_port, credential_id) VALUES (?, ?, ?, ?, ?)',
            [
                serverData.username,
                'server',
                serverData.host,
                serverData.port || 22,
                credResult.insertId
            ]
        );

        return true;
    } catch (error) {
        logger(`[ERROR]:新增服务器信息失败: ${error.message}`);
        throw error;
    }
}

module.exports = {
    getServerInfo,
    addServerInfo
};